package org.example.promise.usage;

import java.io.*;
import java.net.URL;
import java.util.Collections;
import java.util.Comparator;
import java.util.Map;
import java.util.Optional;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * 类描述：Promise的使用示例的工具类
 * <br>
 *
 * @author ZS
 * @version 1.0
 * @date 2020/12/29
 **/
public class Utility {
    // 下载文件并返回文件路径
    public static String downloadFile(String urlString) throws IOException {
        System.out.println("正在下载url的文件" + urlString);
        URL url = new URL(urlString);

        File file = File.createTempFile("promise_pattern", null);
        try (BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(url.openStream()));
             FileWriter writer = new FileWriter(file);) {
            String line;
            while ((line = bufferedReader.readLine()) != null) {
                writer.write(line);
                writer.write("\n");
            }
            System.out.println("下载文件存储位置：" + file.getAbsolutePath());
            return file.getAbsolutePath();
        }
    }

    // 返回文件的行数
    public static Integer countLines(String fileLocation) {
        try(BufferedReader reader = new BufferedReader(new FileReader(fileLocation))) {
            return Math.toIntExact(reader.lines().count());
        } catch (IOException e) {
            e.printStackTrace();
        }
        return 0;
    }

    // 计算每个字符出现的频率
    // frequency：频率
    public static Map<Character, Long> characterFrequency(String fileLocation) {
        try (final BufferedReader reader = new BufferedReader(new FileReader(fileLocation))){
            return reader.lines()
                    .flatMapToInt(String::chars)
                    .mapToObj(x->(char)x)
                    .collect(Collectors.groupingBy(Function.identity(),Collectors.counting()));
        } catch (IOException e) {
            e.printStackTrace();
        }
        return Collections.emptyMap();
    }

    public static Optional<Character> lowestFrequencyChar(Map<Character, Long> characterFrequency) {
        return characterFrequency
                .entrySet()
                .stream()
                .min(Comparator.comparingLong(Map.Entry::getValue))
                .map(Map.Entry::getKey);
    }
}

